package com.ambitor.ipro.actions;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.ambitor.grass.sql.dao.SuperDao;
import com.ambitor.grass.sql.dao.impl.SuperDaoImpl;
import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.IData;
import com.ambitor.grass.util.data.IDataset;
import com.ambitor.ipro.entities.Result;
import com.ambitor.ipro.service.InstallService;
import com.ambitor.ipro.util.ResultCode;
import com.ambitor.ipro.util.StringUtil;
import com.ambitor.ipro.util.TableName;
import com.ambitor.ipro.util.Utils;
import com.ambitor.ipro.view.Pager;

public class StyleAction extends JsonBaseAction {

	private static final long serialVersionUID = -1641837048613839690L;

	private transient SuperDao dao = null;

	private transient Map<String, String> userStyle = new HashMap<String, String>();

	private Result result = new Result();
	
	public StyleAction() throws SQLException {
		dao = new SuperDaoImpl(pd.getConn());
	}

	@Override
	public Pager getPager() {
		return pager;
	}

	@Override
	public IDataset getDataset() {
		return dataset;
	}

	public Map<String, String> getUserStyle() {
		return userStyle;
	}

	public void setUserStyle(Map<String, String> userStyle) {
		this.userStyle = userStyle;
	}
	
	public Result getResult() {
		return result;
	}

	public void setResult(Result result) {
		this.result = result;
	}

	@SuppressWarnings("unchecked")
	// 查询用户已有样式
	public String queryStyle() throws Exception {
		String userId = pd.getTopUserId();
		if (StringUtils.isNotBlank(userId)) {
			IData param = new DataMap();
			param.put("VUSER_ID", userId);
			IDataset result = dao.executeBaseOnSqlSql("TF_P_USER_STYLE",
					"SEL_STYLE_BY_USERID", param);
			result = Utils.getIntellSettings(dao, result);

			pager.setTotalCount(result.count());
			dataset.addAll(result.subList(pager.getFirst(), pager.getEnd()));

			logger.info("共" + pager.getTotalCount() + "条记录");
			logger.info("共" + pager.getTotalPages() + "页");
			logger.info("当前请求的是第" + pager.getCurPageNo() + "页");
			logger.info("从过滤后的结果集中取出从" + (pager.getFirst() + 1) + "到"
					+ pager.getEnd() + "共" + dataset.count() + "条记录.");
		}

		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	// 保存样式
	public String styleSave() throws Exception {
		IData userStyleMap = buildUserStyle();

		IDataset dataset = dao.queryList(TableName.TF_P_USER_STYLE,
				userStyleMap);
		logger.info("dataset.size()="+dataset.size());
		if(dataset.size() > 0){
			result.setCode(ResultCode.ERROR);
			result.setMsg("该样式已存在不需要再新建！该样式名称为："+dataset.get(0, "STYLE_NAME").toString()+"，样式编码为："+dataset.get(0, "STYLE_ID").toString()+"。请点击取消，选择已有样式，谢谢！");
			return SUCCESS;
		}
		InstallService installSvc = new InstallService(pd.getConn());
		installSvc.saveUserStyle(userStyleMap, pd.getUserSession());
		result.setCode(ResultCode.SUCCESS);
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	private IData buildUserStyle() throws Exception {
		IData userStyleMap = new DataMap(userStyle);
		userStyleMap.put("USER_ID", pd.getTopUserId());
		if (userStyle == null) {
			logger.warn("userStyle==null");
		}
		String keyWords = userStyle.get("KEY_WORDS");
		StringBuilder sb = new StringBuilder();
		if (StringUtils.isNotBlank(keyWords)) {
			String[] keyWordArray = keyWords.split("[\\s]+");
			for (String kw : keyWordArray) {
				sb.append(kw);
				sb.append(",");
			}
		}
		keyWords = StringUtil.trimSuffix(sb.toString(), ",");
		userStyleMap.put("KEY_WORDS", keyWords);
		return userStyleMap;
	}

}
